<?php

class LoginController extends Zend_Controller_Action
{

    public function init()
    {
        $this->_helper->layout->disableLayout();
        $this->_helper->layout()->setLayout('layout-login');
    }

    public function indexAction()
    {
    	$this->view->error = '';
    	if ($this->getRequest()->isPost()) {
    		$dbAdapter = Zend_Db_Table_Abstract::getDefaultAdapter();
    		$authAdapter = new Zend_Auth_Adapter_DbTable($dbAdapter);
 		
			$authAdapter
			    ->setTableName('usuarios')
			    ->setIdentityColumn('login')
			    ->setCredentialColumn('password')
			    ->setIdentity($this->getRequest()->getPost('login'))
			    ->setCredential($this->getRequest()->getPost('password'));
		
			$result = Zend_Auth::getInstance()->authenticate($authAdapter);
		
	    	if ($result->isValid()) {
				// los datos del usuario son correctos
				$storage = Zend_Auth::getInstance()->getStorage();
				$resultRow = $authAdapter->getResultRowObject();
				$storage->write($resultRow);
				
	    		$this->_redirect("/admin/");
			} else {
				// datos incorrectos, podr�amos mostrar un mensaje de error
				$form = new Application_Form_Usuarios();
				
			    switch ($result->getCode()) {
			        case Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND:
			        case Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID:
			            // password erroneo
			            $this->view->error =  "<p>L'usuari o password no son correctes</p>";
			            break; 
			        default:
			            /* otro error */
			            break;
			    }
	    		$this->view->form = $form;
			}
    	}
    	else
    	{
	    	$form = new Application_Form_Usuarios();
	    	$this->view->form = $form;
    	}
    }

    public function logoutAction()
    {
       $auth = Zend_Auth::getInstance();
       $auth->clearIdentity();
       $this->_redirect('/login');
    }
}

